<template>
	<view>
		<u--form labelPosition="left" ref="uForm">
			<u-form-item label="姓名" prop="userInfo.username" borderBottom ref="item1">
				<u--input v-model="userInfo.username" border="none" placeholder="请输入用户名"></u--input>
			</u-form-item>

			<u-form-item label="密码" prop="userInfo.password" borderBottom ref="item1">
				<u--input v-model="userInfo.password" border="none" password placeholder="请输入密码"></u--input>
			</u-form-item>

			<u-button size="normal" type="primary" text="登录"
				color="linear-gradient(to right, rgb(85,99,75), rgb(180,196,167))" @click="toLogin">
			</u-button>
		</u--form>
	</view>
</template>

<script>
	import {
		post
	} from '@/utils/request';
	import { jwtDecode } from 'jwt-decode';
	export default {
		data() {
			return {
				userInfo: {
					username: "444",
					password: "111111"
				}
			}
		},
		methods: {

			async toLogin() {
			  console.log("---click----", this.userInfo);
			
			  try {
			    const res = await post('/auth/login', this.userInfo);
			
			    if (res.code === 200) {
			      const token = res.data.access_token;
			
			      // 解析 Token
			      let decoded = null;
			      try {
			        decoded = jwtDecode(token);
			        console.log("Token 解析结果：", decoded);
			      } catch (err) {
			        console.error("Token 解析失败", err);
			      }
			
			      // 提取用户信息（根据你的 Token 字段调整）
			      const userId = decoded?.user_id || decoded?.id || null;
			      const userName = decoded?.username || null;
			
			      // 存到缓存
			      uni.setStorageSync('token', token);
			      if (userId) uni.setStorageSync('userId', userId);
			      if (userName) uni.setStorageSync('userName', userName);
			
			      uni.showLoading({
			        title: '登录成功'
			      });
			
			      setTimeout(() => {
			        uni.hideLoading();
			        uni.switchTab({
			          url: '/pages/first/first'
			        });
			      }, 2000);
			
			    } else {
			      uni.showToast({
			        title: res.msg || '用户名或密码错误',
			        icon: 'error',
			        duration: 2000
			      });
			    }
			
			  } catch (err) {
			    console.error("登录请求出错：", err);
			    uni.showToast({
			      title: '登录失败，请重试',
			      icon: 'error',
			      duration: 2000
			    });
			  }
			}

		}
	};
</script>

<style lang="scss">
	@import "@/uni_modules/uview-ui/index.scss";
</style>